package com.tansuo365.test1.controller.kucunstuff;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tansuo365.test1.bean.kucunbean.TuikuDetails;
import com.tansuo365.test1.bean.kucunbean.TuikuZong;
import com.tansuo365.test1.service.kucunservice.*;
import com.tansuo365.test1.service.otherservice.HuishouZhixingService;
import com.tansuo365.test1.util.DateUtil;
import com.tansuo365.test1.util.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退库单
 */
@PropertySource(value = "classpath:danhao.properties")
@Api(value = "退库单相关控制层", tags = "", description = "")
@RestController
@RequestMapping("/admin/tuikudan")
public class TuikuDanController {

    @Autowired
    private TuikuZongService tuikuZongService;
    @Autowired
    private TuikuDetailsService tuikuDetailsService;
    @Autowired
    private ChukuZhixingService chukuZhixingService;
    @Autowired
    private WuliaoKucunRiZhiService wuliaoKucunRiZhiService;
    @Autowired
    private HuishouZhixingService huishouZhixingService;
    @Autowired
    private ChukuZongService chukuZongService;

    //    @Autowired
//    private TuikuDetailsService tuikuDetailsService;
    @Value("${danhao.tuikudan.prefix}")
    private String tuikudanPrefix;

    //到货单号生成

    /**
     * 获取tuiku单号 OK
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Async
    @RequestMapping("/getTuikuNumber")
    public ListenableFuture<String> genBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(tuikudanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxTuikuDanNumber = tuikuZongService.getTodayMaxTuikuDanNumber();
        if (todayMaxTuikuDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxTuikuDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
    }

    @RequestMapping("/getSelective")
    public Map<String, Object> getTuikuDan(TuikuZong tuikuZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (tuikuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<TuikuZong> tuikuZongsList = tuikuZongService.listTuikuZong(tuikuZong);
        PageInfo<TuikuZong> pageInfo = new PageInfo<>(tuikuZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    @RequestMapping("/listDetailsByZId")
    public Map<String, Object> listDetailsByZongId(TuikuDetails tuikuDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (tuikuDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<TuikuDetails> tuikuDetailsList = tuikuDetailsService.listTuikuDetailsSelective(tuikuDetails);
        PageInfo<TuikuDetails> pageInfo = new PageInfo<>(tuikuDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    /**
     * 保存
     * 1.退库单保存后,同时写入出库数量,退库数量到出库执行汇总
     * 2.退库单保存后,同时写入库存查询表,出库量/退库量,进行计算的(未退回量)
     *
     * @param session
     * @param tuikuZong
     * @param wuliaoTuikuDetailsJson
     * @return
     */
    @RequestMapping("/save")
    public Map<String, Object> save(HttpSession session, TuikuZong tuikuZong, @RequestParam("wuliaoTuikuDetailsJson") String wuliaoTuikuDetailsJson) {
        if (tuikuZong == null || wuliaoTuikuDetailsJson == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        Gson gson = new Gson();
        List<TuikuDetails> tuikuDetailsList = gson.fromJson(wuliaoTuikuDetailsJson, new TypeToken<List<TuikuDetails>>() {
        }.getType());
        tuikuZong.setFounder((String) session.getAttribute("truename"));
        //save时, 先保存大表, 大表返回id后再保存附表
        int insertCode = tuikuZongService.saveZongAndDetails(tuikuZong, tuikuDetailsList);
        int zhixingSaveCode = chukuZhixingService.saveTuikuBindChuku(tuikuDetailsList, tuikuZong);

        if (insertCode > 0 && zhixingSaveCode > 0) {
            resultMap.put("success", true);
            resultMap.put("msg", "保存成功.");
            return resultMap;
        } else if (insertCode == 0) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败");
            return resultMap;
        } else {
            TuikuDetails tuikuDetails = tuikuDetailsList.get((-(insertCode) - 1));
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败,保存物料[" + tuikuDetails.getMingchengguige() + "]不存在库存中.");
            return resultMap;
        }
    }

    @RequestMapping("/update")
    public Map<String, Object> update(TuikuZong tuikuZong) {
        if (tuikuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        int updateCode = tuikuZongService.updateByPrimaryKeySelective(tuikuZong);
        if (updateCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

    @RequestMapping("/delete")
    @Transactional
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") Integer[] ids) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行删除");
            return resultMap;
        }
        //删除退库绑定出库
        int ziDelCode = 0;
        int delBindCode = tuikuZongService.deleteTuikuBindChuku(ids);
        int delToKC = wuliaoKucunRiZhiService.insertButDeleteTuikuShu(ids);
        int code = tuikuZongService.deleteBatchByPKArr(ids);  //批量删除tuiku主表
        List<String> chukudans = null;
        if(code>0){
            //删除之前获取对应的出库单号s
            chukudans = tuikuDetailsService.listDuiyingChukuDan(ids);
            //再删除
            ziDelCode = tuikuDetailsService.deleteByZongIdArr(ids); //批量删除tuiku详细根据ids条目
        }
        if(ziDelCode>0){
//            再判定是否还有这些对应出库单
            List<TuikuDetails> tuikuDetails = tuikuDetailsService.listByDuiyingChukudans(chukudans);
            if(CollectionUtils.isEmpty(tuikuDetails)){
                for(String chukudan:chukudans){
                    int i = chukuZongService.updateCanDeleteNotBindTuiku(chukudan);
                }
            }
        }
        if (code > 0 && ziDelCode > 0 && delBindCode > 0 && delToKC > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }


}
